package com.dingreading.cloud.common.base;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dingreading.cloud.common.util.ErrorCode;
import com.dingreading.cloud.common.util.ExceptionLogs;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 基础VO
 */
@Data
public class BaseVO {

    /**
     * logger
     */
    protected static Logger logger = LoggerFactory.getLogger(BaseVO.class);
    /**
     * 状态码 200成功/500失败
     */
    private Integer st;
    /**
     * 提示信息 操作成功/失败
     */
    private String msg;

    /**
     * 日志输出
     *
     * @param e 异常
     */
    public static void logInfo(Exception e) {
        try {
            if (e.getMessage() != null) {
                String message = e.getMessage();
                if (message.getBytes("GBK").length != message.length()) {
                    //报错信息有自定义中文，不输出详细错误，避免文件过大
                    logger.error(message);
                } else {
                    logger.error(ExceptionLogs.getErrorInfoFromException(e));
                }
            } else {
                logger.error(ExceptionLogs.getErrorInfoFromException(e));
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    /**
     * 操作成功
     *
     * @return baseVO
     */
    public BaseVO success() {
        BaseVO baseVO = new BaseVO();
        baseVO.setSt(ErrorCode.SUCCESS.getCode());
        baseVO.setMsg(ErrorCode.SUCCESS.getMessage());
        return baseVO;
    }

    /**
     * 操作成功
     *
     * @return baseVO
     */
    public BaseVO success(BaseVO baseVO) {
        baseVO.setSt(ErrorCode.SUCCESS.getCode());
        baseVO.setMsg(ErrorCode.SUCCESS.getMessage());
        return baseVO;
    }

    /**
     * 操作失败
     *
     * @return baseVO
     */
    public BaseVO error(BaseVO baseVO, Exception e) {
        String message = ErrorCode.SYSTEM_ERROR.getMessage();
        baseVO.setSt(ErrorCode.SYSTEM_ERROR.getCode());
        logInfo(e);
        try {
            if (e.getMessage() != null && e.getMessage().getBytes("GBK").length != e.getMessage().length()) {
                //报错信息有自定义中文，按自定义为准
                message = e.getMessage();
            }
        } catch (Exception ex) {
            baseVO.setMsg(message);
            return baseVO;
        }
        baseVO.setMsg(message);
        return baseVO;
    }

    @Override
    public String toString() {
        return JSONObject.toJSONString(this, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
    }

}
